<template>
  <div class="mainos">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline marginTop0"
          ref="userListFrom"
          label-width="60px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>审核入库单</span>
            </div>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>单据信息</div>
          </div>
          <div class="main_xq">
            <ul class="boxha">
              <li>
                入库单号：<span>{{ info.order_sn }}</span>
              </li>
              <li>
                入库类型：<span
                  >{{ base.typeList[info.type] }}</span
                >
              </li>
              <li>
                制单人：<span>{{ info.admin_user_name.name }}</span>
              </li>
              <li>
                创建时间：<span>{{
                  parseTime(info.created_at, "{y}-{m}-{d}")
                }}</span>
              </li>
              <li>
                关联单号：<span>{{ info.related_order_sn }}</span>
              </li>
              <li>
                采购类型：<span>{{ base.modeList[info.mode] }}</span>
              </li>
              <li>
                采购员/供应商：<span>{{
                info.mode == 1
                  ? base.buyer[info.buyer_id]
                  : base.supplier[info.supplier_id]
              }}</span>
              </li>
              <li class="main_w100 box">
                备注：
                <div class="box main_xqi" style="margin-top: -4px">
                  <el-input
                    v-model.trim="monitorForm.form.remark"
                    placeholder="备注"
                    clearable
                    style="width: 100%"
                  ></el-input>
                </div>
              </li>
            </ul>
          </div>
          <div class="main_tile boxdq marginTop15">
            <div class="main_tile_l marginLeft0"><em></em>商品详情</div>
          </div>
          <div class="main_white padding10 marginBottom10">
            <div class="main_white">
              <div class="boxdq boxha">
                <div class="mainor_sp boxdq" v-if="info.type==2">
                  <div class="box">
                    <ul class="box">
                      <li class="box">
                        <span> <em>*</em>商品名称： </span>
                        <el-autocomplete
                          v-model="formsp.value"
                          ref="searchSelect"
                          class="wid240 main_comm"
                          @clear="$refs.searchSelect.$children[0].blur()"
                          :fetch-suggestions="
                            (queryString, cb) => {
                              querySearchAsync(queryString, cb);
                            }
                          "
                          placeholder="商品名称/别名/编码/助记码"
                          clearable
                          :highlight-first-item="true"
                          value-key="name"
                          @select="
                            (item) => {
                              handleSelect(item);
                            }
                          "
                        >
                          <template slot-scope="{ item }">
                            <div class="main_name">
                              {{ item.goods.name }}【{{ item.spu_unit.title }}】
                            </div>
                            <span class="main_addr" v-if="info.show_sku_code == 1">{{
                              item.goods_spu_code
                            }}</span>
                          </template>
                        </el-autocomplete>
                      </li>
                      <li class="box">
                        <span> <em>*</em>数量： </span>
                        <el-input
                          v-model.trim="formsp.num"
                          ref="focusw2"
                          placeholder="数量"
                          clearable
                          class="wid140"
                          @keyup.enter.native="mainor_sp"
                        ></el-input>
                      </li>
                    </ul>
                    <div class="marginBottom10">
                      <el-button type="primary" @click="mainor_qr"
                        >确认(回车)</el-button
                      >
                      <el-button class="reset marginLeft5" type="info" @click="reset"
                        >重置</el-button
                      >
                    </div>
                  </div>
                </div>
                <div class="mainor_sp boxha">
                  <ul class="box">
                    <li class="box">
                      <el-input
                        v-model.trim="formzd.value"
                        ref="focusw2"
                        placeholder="商品名称"
                        clearable
                        class="wid240"
                        @keyup.enter.native="mainor_zd"
                      ></el-input>
                    </li>
                  </ul>
                  <div class="marginBottom10">
                    <el-button type="primary" @click="mainor_zd"
                      >置顶(回车)</el-button
                    >
                    <el-button
                      class="reset marginLeft5"
                      type="info"
                      @click="formzd.value = ''"
                      >重置</el-button
                    >
                  </div>
                </div>
              </div>
              <div class="main_table marginTop0">
                <el-table
                  ref="multipleTable"
                  :data="monitorForm.list"
                  element-loading-text="加载中"
                  fit
                  border
                  highlight-current-row
                >
                  <el-table-column label="序号">
                    <template slot-scope="scope">{{
                      scope.$index + 1
                    }}</template>
                  </el-table-column>
                  <el-table-column label="商品名称" prop="name" width="150">
                    <template slot-scope="scope"
                      ><div v-if="scope.row.show">{{ scope.row.goods.name }}【{{
                        scope.row.goods_spu.spu_name.title
                      }}】</div><div v-else>{{ scope.row.name }}</div></template
                    >
                  </el-table-column>
                  <el-table-column label="单位" prop="goods_spu.spu_unit.title" >
                    <template slot-scope="scope"><div v-if="scope.row.show">{{
                        scope.row.goods_spu.spu_unit.title
                      }}</div><div v-else>{{ scope.row.unit }}</div></template>
                  </el-table-column>
                  <el-table-column label="应入库数量" prop="num" width="130" />
                  <el-table-column
                    label="实入库数量"
                    prop="storage_num"
                    width="150"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'list.' + scope.$index + '.storage_num'"
                        :rules="rules.storage_num"
                        label-width="10px"
                        label=" "
                      >
                        <el-input
                          v-model.trim="scope.row.storage_num"
                          :ref="'storage_num' + scope.row.goods_spu_id"
                          @input="scope.row.xs=false"
                          placeholder="数量"
                          class="wid110"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单价"
                    prop="price"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">{{ scope.row.id?scope.row.xs?scope.row.price:(scope.row.money/scope.row.storage_num?(scope.row.money/scope.row.storage_num).toFixed(2):0):scope.row.price }}</template>
                  </el-table-column>
                  <el-table-column
                    label="入库金额"
                    prop="un_purchase_num"
                    class-name="main_hei"
                    width="130"
                  >
                    <template slot-scope="scope">{{ scope.row.id?scope.row.money:(parseFloat(scope.row.storage_num) * parseFloat(scope.row.price)?(parseFloat(scope.row.storage_num) * parseFloat(scope.row.price)).toFixed(2):0) }}</template>
                  </el-table-column>
                  <el-table-column
                    label="备注"
                    prop="remark"
                    width="350"
                    class-name="main_hei"
                  >
                    <template slot-scope="scope">
                      <el-form-item label-width="0" label="">
                        <el-input
                          v-model.trim="scope.row.remark"
                          placeholder="备注"
                          class="wid240"
                        ></el-input>
                      </el-form-item>
                      <el-link
                        type="danger"
                        @click="scope.row.show?(lengt<=1?'':scdelete(scope.$index,true)):scdelete(scope.$index)"
                        v-if="info.type==2"
                        class="paddingTop20"
                        >删除</el-link
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
          <div class="newConBox_p200 paddingBottom10" id="newConBox">
            <div class="newConBox_h32">
              <div
                :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
              >
                <div class="mainor_prl">
                  <el-button
                    type="primary"
                    @click="preservation(1)"
                    v-repeatClick
                    >保存并通过</el-button
                  >
                  <el-button v-repeatClick @click="preservation(2)" v-if="info.type==2"
                    >取消入库</el-button
                  >
                  <el-button @click="$router.back(-1)">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
const shuju = {
  list: {
    id: "",
    name: "",
    goods_id: "",
    goods_spu_id: "",
    spu_name: "",
    unit: "",
    price: "",
    num: "",
    storage_num: "",
    remark: "",
    show: false,
  },
  form: {
    remark: "",
  },
  formsp: {
    name: [],
    girard: null,
    num: "",
    value: "",
  },
};
import {
  storage_info,
  storage_base,
  storage_getInventory,
  storage_check,
  storage_deleteList
} from "@/api/warehouse/warehouseReceipt";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseReceipt_edit";
import { parseTime } from "@/utils/index";
import { goods_getGoodsSpu } from "@/api/currency";

export default {
  computed:{
    lengt(){
      let zj=0
      this.monitorForm.list.map(e=>{
        if(e.show){
          zj++
        }
      })
      return zj
    }
  },
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 时间
      parseTime,
      // 基本信息
      info: {
        created_at: "2000-01-01",
        updated_at: "2000-01-01",
        type:0,
        status:0,
        mode:0,
        storage_list:[],
      },
      base:{
        modeList: ["后台"],
        buyer: ["后台"],
        supplier: ["后台"],
        typeList: ["待审核"],
      },
      listLoading: false,
      // 列表数据
      monitorForm: {
        form: {
          remark: "",
        },
        list: [],
      },
      // 商品搜索
      formzd: {
        value: "",
      },
      formsp: {
        name: [],
        girard: null,
        num: "",
        value: "",
      },
      price: "",
      show: true,
      // id
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
    // 基本信息
    this.storage_info();
    this.storage_base();
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          res.data.goods.map((e) => {
            e.name = e.goods.name + "【" + e.spu_unit.title + "】";
          });
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.formsp.name = item;
      this.formsp.girard = item.id;
      this.storage_getInventory();
    },
    storage_getInventory() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                goods_id: formsp.name.goods_id,
                goods_spu_id: formsp.girard,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          goods_id: formsp.name.goods_id,
          goods_spu_id: formsp.girard,
        }
      );
      storage_getInventory(data).then((res) => {
        if (res.errcode == 0) {
          this.price = res.data.data.price;
          setTimeout(() => {
            this.$refs.focusw2.focus();
          }, 100);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.name.name) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let monitorForm_list = JSON.parse(
          JSON.stringify(this.monitorForm.list)
        );
        let ind = 0;
        if (monitorForm_list.length != 0) {
          monitorForm_list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.handle(formsp);
          } else {
            setTimeout(() => {
              this.$refs["storage_num" + ind].focus();
              this.reset();
              ind = 0;
            }, 100);
          }
        } else {
          this.handle(formsp);
        }
      }
    },
    handle(formsp) {
      let list = JSON.parse(JSON.stringify(shuju.list));
      list.name = formsp.name.goods.name;
      list.goods_id = formsp.name.goods_id;
      list.goods_spu_id = formsp.name.id;
      list.spu_name = formsp.name.spu_name.title;
      list.unit = formsp.name.spu_unit.title;
      list.price = this.price;
      list.num = formsp.num;
      list.storage_num = formsp.num;
      list.remark = formsp.name.remark;
      this.monitorForm.list.push(list);
      this.reset();
      setTimeout(() => {
        this.$refs.searchSelect.focus();
      }, 100);
    },
    reset() {
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    // 置顶
    mainor_zd() {
      let formzd = JSON.parse(JSON.stringify(this.formzd));
      let list = JSON.parse(JSON.stringify(this.monitorForm.list));
      if (formzd.name != "") {
        list.map((e, index) => {
          if (e.name.includes(formzd.value)) {
            let sz = {};
            sz = e;
            list.splice(index, 1);
            list.unshift(sz);
          }
        });
        this.monitorForm.list = list;
      }
    },
    // 删除
    scdelete(index,type) {
      if(type){
        let data = Object.assign(
          {
            sign: Md5(
              objKeySort(Object.assign(apiUrl().name, { id: this.monitorForm.list[index].id })) +
                apiUrl().appsecret
            ),
          },
          apiUrl().name,
          { id: this.monitorForm.list[index].id }
        );
        storage_deleteList(data).then((res) => {
          if (res.errcode == 0) {
            this.monitorForm.list.splice(index, 1);
          } else {
            this.$message.error(res.errmsg);
          }
        });
      }else{
        this.monitorForm.list.splice(index, 1);
      }
    },
    // 保存
    preservation(type) {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if(type==2){
            this.$confirm("确定取消入库?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.storage_check(type);
            })
            .catch(() => {});
            return
          }
          this.storage_check(type);
        }
      });
    },
    storage_check(type){
      let arry = [];
      let monitorForm = JSON.parse(JSON.stringify(this.monitorForm));
      monitorForm.list.map((e) => {
        arry.push({
          id:e.id?e.id:null,
          goods_id: e.goods_id,
          goods_spu_id: e.goods_spu_id,
          remark: e.remark,
          num: e.num,
          storage_num: e.storage_num,
          price: e.price,
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id,status:type })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        monitorForm.form,
        {
          list: JSON.stringify(arry),
          id: this.id,
          status:type
        }
      );
      storage_check(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.$router.go(-1);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 基本信息
    storage_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      storage_info(data).then((res) => {
        if (res.errcode == 0) {
          res.data.info.storage_list.map(e=>{
            e.storage_num=e.num
            e.show=true
            e.xs=true
          })
          this.monitorForm.list = res.data.info.storage_list
          this.monitorForm.form.remark = res.data.info.remark
          this.info = res.data.info;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    storage_base() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      storage_base(data).then((res) => {
        if (res.errcode == 0) {
          this.base = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainos {
  .main_tile {
    .mainos_tile_r {
      color: $colour_red;
      font-size: $font_14;
    }
  }
  .newConBox.on {
    margin-left: -10px;
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
  .main_xq {
    ul {
      li {
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
        .main_upImg {
          /deep/ul {
            li {
              padding-left: 0;
            }
          }
          /deep/.el-upload-list--picture-card
            .el-upload-list__item:first-child {
            margin-left: 145px;
          }
        }
      }
    }
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
    .mainor_prr {
      font-size: $font_16;
      color: $colour_18;
      span {
        color: #fe3b3b;
        margin-left: 10px;
      }
    }
  }
  .base_p {
    width: 80px;
  }
  .main_page_top {
    margin-top: 7px;
    margin-left: 10px;
    use {
      fill: $menuText;
    }
    &:hover {
      cursor: pointer;
      use {
        fill: $menuActiveText;
      }
    }
  }
}
</style>
